#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Offline log player:
reads log/monitor_log.jsonl and prints two lines (summary + detail)
every INTERVAL seconds, then exits when the file is exhausted.
"""

import json
import time
import os

# ───── 固定配置 ─────
LOG_PATH  = "log/monitor_log.jsonl"  # 日志文件路径
INTERVAL  = 1.0                      # 两行之间的输出间隔（秒）

# ───── 文件检查 ─────
if not os.path.isfile(LOG_PATH):
    raise FileNotFoundError(f"日志文件不存在: {LOG_PATH}")

# ───── 读取全部行（去掉空行 / 换行）─────
with open(LOG_PATH, "r", encoding="utf-8") as fp:
    lines = [ln.strip() for ln in fp if ln.strip()]

# 若行数为奇数，丢弃最后一行不完整数据
if len(lines) % 2 == 1:
    lines = lines[:-1]

# ───── 按 2 行一组输出 ─────
for idx in range(0, len(lines), 2):
    summary_raw = lines[idx]
    detail_raw  = lines[idx + 1]

    try:
        # 解析后美化打印（也可以直接 print 原字符串）
        summary_json = json.loads(summary_raw)
        detail_json  = json.loads(detail_raw)

        print("Summary JSON:")
        print(json.dumps(summary_json, indent=2, ensure_ascii=False))
        print("Detail JSON:")
        print(json.dumps(detail_json,  indent=2, ensure_ascii=False))
    except json.JSONDecodeError:
        # 如果不是合法 JSON，原样输出
        print(summary_raw)
        print(detail_raw)

    # 最后一组打印完就退出；否则暂停 INTERVAL 秒
    if idx + 2 < len(lines):
        time.sleep(INTERVAL)
